package com.rds.benchmark.connector;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.util.JedisClusterCRC16;

import java.util.HashSet;
import java.util.Set;

public class ClusterJedisConnector implements JedisConnector {

    private final JedisCluster cluster;

    private String stringDes;

    public ClusterJedisConnector(final String host, final int port, final int max_threads, final String password) {
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxTotal(max_threads + 1);
        poolConfig.setMaxIdle(max_threads + 1);

        Set<HostAndPort> hostAndPortsSet = new HashSet<>();
        // 添加节点
        hostAndPortsSet.add(new HostAndPort(host, port));

        cluster = new JedisCluster(hostAndPortsSet, TIME_OUT, TIME_OUT, MAX_ATTEMPTS, password, poolConfig);

        stringDes = "ClusterJedisConnector(host='" + host + "', port='"+ port +"' )";
        System.out.println(stringDes + " connecting....");
    }

    @Override
    public Object getJedis() {
        return cluster;
    }


    @Override
    public boolean test() {
        try(Jedis jedis = new Jedis(cluster.getConnectionFromSlot(0))) {
            return "PONG".equalsIgnoreCase(jedis.ping());
        }
    }

    @Override
    public String type() {
        return "CLUSTER";
    }

    @Override
    public String toString() {
        return stringDes;
    }
}
